package com.example.envctel;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.LinkAddress;
import android.net.ProxyInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.sql.Array;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Timer;

import static android.os.SystemClock.sleep;

public class MainActivity extends AppCompatActivity {

    TextView tv;

    int  retlen = 0x00;
    static int cycleflag1 = 0x00;
    int autoModeFlag = 0x00;

    static int usbSerialStatus = 0x00;
    int initModBusServerSuccessFlag = 0x00;

    static int [] setvalue = new int[1];
    static int [] getvalue = new int[1];
    static int [] lightvalue = new int[5];
    static int [] lightvalue1 = new int[5];
    static int [] irSensorStatus = new int[1];
    static int [] lastIrSensorStatus = new int[1];
    static int [] irSensorStatus1 = new int[1];
    static int [] lastIrSensorStatus1 = new int[1];
    static int []  dimmerControllerWorkMode = new int[1];
    static int [] curtainMotorControllerData = new int[16];

    static  int timerCnt = 0;
    byte[] pvalue = new byte[256];

    int shiJuLightController = 0x03;
    int diKongLightController_Trace = 0x01;
    int diKongLightController_0_10 = 0x05;

    environmentControl environmentControl = new environmentControl();
    Handler handler = new Handler();
    Handler handler1 = new Handler();
    Handler handler2 = new Handler();
    Handler handler3 = new Handler();
    Handler handler4 = new Handler();
    Handler handler5 = new Handler();

    private static MainActivity mainActivity;

    public MainActivity() {
        mainActivity = this;
    }

    public static MainActivity getMainActivity() {
            return mainActivity;
    }

    static {
        System.loadLibrary("envCtrolLib");
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
                .build());

        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart()
    {

        int i = 0x00;
        super.onStart();
        System.out.println("onStart");

        /**申请运行时权限
         * *
         * */
        if(Build.VERSION.SDK_INT >= 23){
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            }
        }

        /*
        * 获取中心ip地址并显示
        * */
        getNetParam();


        Intent intentTcpServer = new Intent(this,MyTcpService.class);
        startService(intentTcpServer);

        /**/
        environmentControl.initTCPServer();

        new Thread(new Runnable() {
            @Override
            public void run() {
                handler.post(showRunnable);
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler2.post(showRunnable2);
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler3.post(showRunnable3);
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler4.post(showRunnable4);
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler5.post(showRunnable5);
            }
        }).start();
    }

    /************************************************************************************
    * 光照度采集
    * 自动调节灯光亮度
    *光照度亮灭渐变
    * ************************************************************************************/
    Runnable showRunnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(showRunnable, 1000);//在这里设置延时时间，单位是毫秒
            {
                if ((timerCnt ++) >= 5)
                {
                    timerCnt = 0x00;
                    getvalue[0] = 0x00;

                    /*查询光照度参数 :通过调光控制器查询当前实际的光照度*/
                    environmentControl.getModbusDeviceInfo(diKongLightController_Trace,2,0x05,1,getvalue);
                    System.out.println("调光控制器模块：光照度实际值:" + getvalue[0]);

                    /*查询光照度参数:直接通过光照度传感器查询*/
                    environmentControl.getModbusDeviceInfo(0x04,2,0x05,1,getvalue);
                    System.out.println("光照度实际值:" + getvalue[0] * 10);
                }

                //if (autoModeFlag == 0x01)
                {

                    if (cycleflag1 == 0x00)
                    {
                        if (lightvalue[0] > 0x00)
                        {
                            lightvalue[0] -= 10;
                        }
                        else
                        {
                            cycleflag1 = 0x01;
                        }
                    }
                    else if (cycleflag1 == 0x01)
                    {
                        if (lightvalue[0] < 1000)
                        {
                            lightvalue[0] += 10;
                        }
                        else
                        {
                            cycleflag1 = 0x00;
                        }
                    }

                    /*调节灯管亮度*/
                    retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x34,1,lightvalue);
                }
            }
        }
    };

    /**
     * *
     * *定时：定时检测红外接近传感器状态
     * *     检测到红外接近传感器触发状态 : 设置第二路灯光亮度；%50，设置第三路灯光亮度：%100
     * **    未检测到红外接近传感器触发状态 : 设置第二路灯光亮度；%0，设置第三路灯光亮度：%50
     * *
     * *
     * */
    Runnable showRunnable2 = new Runnable() {
        @Override
        public void run() {

            handler2.postDelayed(showRunnable2, 1000);//在这里设置延时时间，单位是毫秒 1s

            //在这里进行想做的事
            if(autoModeFlag == 0x01)
            {
                /*查询红外接近传感器状态 :控制调光控制器 模块亮度调节*/
                //retlen = environmentControl.getModbusDeviceInfo(2,2,0x03,1,irSensorStatus);
                retlen = environmentControl.getModbusDeviceInfo(0x0a,2,0x00,1,irSensorStatus);
                if (lastIrSensorStatus[0] != irSensorStatus[0])
                {

                    lastIrSensorStatus[0] = irSensorStatus[0];
                    if ((irSensorStatus[0] == 0x01))
                    {
                        /*全亮 :%100*/
                        lightvalue1[0] = 0x01;
                        environmentControl.setModbusDeviceInfo(shiJuLightController,2,0x04,1,lightvalue1);

                        /*亮度 :%50*/
                        lightvalue1[0] = 0x40;
                        environmentControl.setModbusDeviceInfo(shiJuLightController,2,0x0f,1,lightvalue1);
                    }
                    else
                    {
                        lightvalue1[0] = 0x00;
                        environmentControl.setModbusDeviceInfo(shiJuLightController,2,0x02,1,lightvalue1);

                        lightvalue1[0] = 0x00;
                        environmentControl.setModbusDeviceInfo(shiJuLightController,2,0x11,1,lightvalue1);
                    }
                }

                /*查询红外接近传感器状态 :控制调光控制器 模块亮度调节*/
                retlen = environmentControl.getModbusDeviceInfo(0x10,0x00,0x00,1,irSensorStatus1);

                if (lastIrSensorStatus1[0] != irSensorStatus1[0])
                {

                    lastIrSensorStatus1[0] = irSensorStatus1[0];
                    if ((irSensorStatus1[0] == 0x01))
                    {
                        /*全亮 :%100*/
                        lightvalue1[0] = 1000;
                        retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x34,1,lightvalue1);

                        /*亮度 :%50*/
                        lightvalue1[0] = 1000;
                        retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x35,1,lightvalue1);

                    }
                    else
                    {
                        lightvalue1[0] = 0x00;
                        environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x34,1,lightvalue1);

                        lightvalue1[0] = 0x00;
                        environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x35,1,lightvalue1);
                    }
                }
            }
        }
    };


    Runnable showRunnable3 = new Runnable() {
        @Override
        public void run() {

            int i = 0x00;
            int ret = 0x00;

            handler3.postDelayed(showRunnable3, 1000);//在这里设置延时时间，单位是毫秒 1s
            {

                ret =  environmentControl.getTCPClientData(pvalue);
                System.out.println("************** system  ret :" + Integer.toString(ret) + "****************");

                if (ret != 0x00)
                 {
                     for(i = 0x00;i < ret;i ++)
                     {
                         System.out.printf("%02x", pvalue[i]);
                     }

                     /*解析接收到的数据帧*/
                     analysisRecvData(pvalue);
                 }

            }

        }
    };

    Runnable showRunnable4 = new Runnable() {
        @Override
        public void run() {

            handler4.postDelayed(showRunnable4, 2000);//在这里设置延时时间，单位是毫秒 1s
            {
                /*开窗帘*/
                System.out.println("====send open curtain command!=====");
                environmentControl.curtainMotorDeviceControlInfo(1,2,3,1,0,curtainMotorControllerData);

                curtainMotorControllerData[0] = 01;
                environmentControl.curtainMotorDeviceControlInfo(1,2,3,9,1,curtainMotorControllerData);

                curtainMotorControllerData[0] = 0x12;
                curtainMotorControllerData[1] = 0x34;
                environmentControl.curtainMotorDeviceControlInfo(1,2,3,0,2,curtainMotorControllerData);

                /*查询设备地址 为3 地址从0开始的两个数据*/
                environmentControl.curtainMotorDeviceControlInfo(1,2,1,0,2,curtainMotorControllerData);

                /*打印获取到的数据*/
                System.out.println("curtaininfo:" + curtainMotorControllerData[0] + curtainMotorControllerData[1]);
                System.out.println(Arrays.toString(curtainMotorControllerData));

                /*设备地址 为6 地址从0开始的两个数据*/
                environmentControl.curtainMotorDeviceControlInfo(2,0xddffff,0xfffe,0,2,curtainMotorControllerData);
            }

        }
    };

    Runnable showRunnable5 = new Runnable() {
        @Override
        public void run() {

            int i = 0x00;
            int ret = 0x00;

            EditText editText;
            handler5.postDelayed(showRunnable5, 1000);//在这里设置延时时间，单位是毫秒 1s
            {
                editText=(EditText)findViewById( R.id.editTextTime);

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
                editText.setText(simpleDateFormat.format(date));
            }

        }
    };

    public  int analysisRecvData(byte[] pvalue) {

            int cnt = 0x00;
            int i = 0x00;

            byte devAddr = 0x00;
            byte funCode = 0x00;
            int startAddr = 0x00;
            int dataNum = 0x00;

            int [] dataBuff  = new int[32];
            int [] LightValue = new int[5];

            /*接收到数据帧头*/
            if(((pvalue[cnt])) == (byte)0xfa)
            {
                    cnt ++;
                    switch(pvalue[cnt])
                    {
                        /*上课:灯全亮*/
                        case 0x00:
                        {
                            autoModeFlag = 0x00;
                            lastIrSensorStatus[0] = -1;

                            /*设置调光模块工作模式:自动控制，根据光照度强度自动调节灯光亮度*/
                            dimmerControllerWorkMode[0] = 0x00;

                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,0,0x1c,1,dimmerControllerWorkMode);
                            if (retlen > 0x00)
                            {
                                System.out.println("调光器模式设置成功，调光器模式：自动");
                            }

                            /*全亮 :%100*/
                            lightvalue1[0] = lightvalue1[1] =lightvalue1[2] =lightvalue1[3] =0x01;
                            environmentControl.setModbusDeviceInfo(shiJuLightController,2,0x01,4,lightvalue1);

                            /*调节灯管亮度*/
                            lightvalue[0] = 1000;
                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x34,1,lightvalue);
                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x35,1,lightvalue);


                            /*灯带全亮：*/
                            lightvalue[0] = 1000;
                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_0_10,2,0x34,1,lightvalue);

//                            /*调节灯管亮度*/
//                            lightvalue[0] = 0x01;
//                            retlen = environmentControl.setModbusDeviceInfo(5,0,0x3,1,lightvalue);
//                            retlen = environmentControl.setModbusDeviceInfo(5,0,0x4,1,lightvalue);
//
//                            retlen = environmentControl.getModbusDeviceInfo(0x05,0x01,0x25,1,irSensorStatus1);
//                            retlen = environmentControl.getModbusDeviceInfo(0x05,0x02,0x05,1,irSensorStatus1);
                        }
                            break;
                        /*下课:灯全灭*/
                        case 0x01:
                        {
                            autoModeFlag = 0x00;
                            lastIrSensorStatus[0] = -1;

                            dimmerControllerWorkMode[0] = 0x00;

                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,0,0x1c,1,dimmerControllerWorkMode);
                            if (retlen > 0x00)
                            {
                                System.out.println("调光器模式设置成功，调光器模式：自动");
                            }

                            lightvalue1[0] = lightvalue1[1] =lightvalue1[2] =lightvalue1[3] =0x00;
                            environmentControl.setModbusDeviceInfo(shiJuLightController,2,0x01,4,lightvalue1);

                            /*调节灯管亮度*/
                            lightvalue[0] = 0;
                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x34,1,lightvalue);
                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x35,1,lightvalue);

                            /*灯带全灭：*/
                            lightvalue[0] = 0x00;
                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_0_10,2,0x34,1,lightvalue);

                        }
                            break;

                        /*自习:灯全部亮度 50%*/
                        case 0x02:
                        {
                            autoModeFlag = 0x00;
                            lastIrSensorStatus[0] = -1;

                            /*设置调光模块工作模式:自动控制，根据光照度强度自动调节灯光亮度*/
                            dimmerControllerWorkMode[0] = 0x00;

                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,0,0x1c,1,dimmerControllerWorkMode);
                            if (retlen > 0x00)
                            {
                                System.out.println("调光器模式设置成功，调光器模式：自动");
                            }

                            lightvalue1[0] = lightvalue1[1] =lightvalue1[2] =lightvalue1[3] =0x20;
                            environmentControl.setModbusDeviceInfo(shiJuLightController,2,0x0e,4,lightvalue1);

                            /*调节灯管亮度*/
                            lightvalue[0] = 500;
                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x34,1,lightvalue);
                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_Trace,2,0x35,1,lightvalue);

                            /*调节灯管亮度*/
                            lightvalue[0] = 500;
                            retlen = environmentControl.setModbusDeviceInfo(diKongLightController_0_10,2,0x34,1,lightvalue);
                        }
                            break;

                        /*未定义:模式切换*/
                        case 0x03:
                        {
                            autoModeFlag = 0x01;
                            lastIrSensorStatus[0] = -1;

                        }
                            break;

                        default:
                        {
                            autoModeFlag = 0x00;
                            lastIrSensorStatus[0] = -1;
                        }
                            break;
                    }
            }
            /*数据转发: 不进行数据处理*/
            else
            {
                /*数据一般包括:地址位、功能码、起始地址、数据长度、数据、校验位*/
                devAddr = pvalue[cnt++];
                funCode = pvalue[cnt++];

                switch(funCode)
                {
                    case 0x05:
                    {

                        /*测试使用指令码 : 0x05*/

                        startAddr = ((pvalue[cnt] & 0xff) <<8);
                        startAddr |= pvalue[cnt + 1] & 0xff;

                        cnt += 2;

                        dataBuff[0] = ((pvalue[cnt] & 0xff) <<8);
                        dataBuff[0] |=  pvalue[cnt + 1] & 0xff;

//                        /*查询当前状态:亮度值*/
                        /*寄存器地址偏移：灯光开关与灯关亮度寄存器偏移为0x0d*/
                        startAddr += 0x0D;
                        retlen = environmentControl.getModbusDeviceInfo(devAddr,2,startAddr,1,LightValue);
                        System.out.format("light value : %x,databuff[0] :%x\n",LightValue[0],dataBuff[0]);

                        /*增加*/
                        if (dataBuff[0] == 0xaa00)
                        {
                            LightValue[0] += 10;
                            if (LightValue[0] > 64)
                            {
                                LightValue[0] = 64;
                            }
                        }
                        /*减少*/
                        else if (dataBuff[0] == 0x3300)
                        {
                            if (LightValue[0] >= 10)
                            {
                                LightValue[0] -= 10;
                            }
                            else
                            {
                                LightValue[0] = 0;
                            }
                        }
                        /*开*/
                        else if (dataBuff[0] == 0xff00)
                        {
                            LightValue[0] = 0x40;
                        }
                        /*关*/
                        else if (dataBuff[0] == 0x0000)
                        {
                            LightValue[0] = 0x00;
                        }
                        environmentControl.setModbusDeviceInfo(devAddr,2,startAddr,1,LightValue);
                    }
                    break;

                    case 0x06:
                    {
                        startAddr = ((pvalue[cnt] & 0xff) <<8);
                        startAddr |= pvalue[cnt + 1] & 0xff;

                        cnt += 2;
                        dataNum = 0x02;

//                        System.out.format( "pvalue :");
//                        for (i = 0x00;i < (dataNum );i ++)
//                        {
//                            System.out.format( "%02x ", pvalue[cnt + i]);
//                        }
//                        System.out.format( "\n");
                        dataBuff[0] = ((pvalue[cnt] & 0xff) <<8);
                        dataBuff[0] |= (pvalue[cnt + 1] ) & 0xff;

                        retlen = environmentControl.getModbusDeviceInfo(devAddr,2,startAddr,1,LightValue);
                        System.out.format("light value : %x,databuff[0] :%x\n",LightValue[0],dataBuff[0]);

                        /*增加*/
                        if (dataBuff[0] == 0xaa00)
                        {
                            LightValue[0] += 100;
                            if (LightValue[0] > 1000)
                            {
                                LightValue[0] = 1000;
                            }

                            dataBuff[0] = LightValue[0];
                        }
                        /*减少*/
                        else if (dataBuff[0] == 0x3300)
                        {
                            if (LightValue[0] >= 100)
                            {
                                LightValue[0] -= 100;
                            }
                            else
                            {
                                LightValue[0] = 0;
                            }

                            dataBuff[0] = LightValue[0];
                        }

                        environmentControl.setModbusDeviceInfo(devAddr,2,startAddr,dataNum/2,dataBuff);

                    }
                        break;

                    default:
                        break;
                }
            }

            return 0x00;
    }

    /**
     * 将String转换为byte[]
     * @param s String
     * @return byte[]
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

	void CharArrayToHexString(byte[] pOut, final byte[] pInput, final int nInLen)
	{

        //final char[] chHexList = new char[]{"0123456789ABCDEF"};
        final byte[] chHexList = new byte[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

	    int nIndex = 0;
	    int i=0, j=0;

	    for (i=0, j=0;i<nInLen;i++, j+=2)
	    {
	        nIndex = pInput[i] & 0xf;
	        pOut[i*2+1] = chHexList[nIndex];
	        nIndex = ((pInput[i]>>4) & 0xf);
	        pOut[i*2] = chHexList[nIndex];
	    }
	}

	void LogOutHexString(byte [] data,int len)
	{
	    int strlen = 2 * len + 1;
	    //char *STR = (char *)malloc(sizeof(char ) *strlen);
        byte[] STR = new byte[strlen];

	    CharArrayToHexString(STR,data,len);
	    System.out.println(Arrays.toString(STR));
	}

	void getNetParam()
    {
        String etherip,wifip;
        TextView textViewEthernetIp,textViewWifiIp;

        etherip = netUtils.getLocalIpByEthernet(this);
        System.out.println("ethernet ip :" + etherip);

        textViewEthernetIp = (TextView)mainActivity.findViewById(R.id.textView16);
        textViewEthernetIp.setText(etherip);

        wifip = netUtils.getLocalIp(this);
        System.out.println("wifi ip :" + wifip);

        textViewWifiIp = (TextView)mainActivity.findViewById(R.id.textView23);
        textViewWifiIp.setText(wifip);
    }
}






